layui.define(['layer','table','form'],function (exports) {
    var layer = layui.layer,table = layui.table,form=layui.form;
    var DEFAULTS = {mid:getUrlParam('mid'),listQuery:false,listCols:false,listQueryArg:{},statusTotal:'',statusElementId:'',winArg:{},
        listQueryDone:function (){},
        toolClick:function (){},
        elem:'.operation-btn',done:function () {}};
    var operation = {
        $elem:null,
        $copy:null,
        $check1:null,//单选
        $check2:null,//多选
        $statusOper:null,//状态控制
        init:function (arg) {
            var $arg = $.extend({},DEFAULTS,arg),backData={mid:$arg.mid,data:{}};
            $('body').append('<input type="text" id="copyContent" value="" style="width: 1px;height: 1px;position: fixed;bottom: 0;left: 0;z-index: 0;background-color: transparent;border: 0px"/>');
            operation.$copy = $('#copyContent');
            $.get(rurl('scm/menu/userOperationMenus'),{'id':$arg.mid},function (res) {
                if(isSuccess(res)){
                    backData.data = res.data;
                    if(backData.data!=null&&backData.data.length>0){
                        $arg.done(backData);//回调
                        operation.$elem = $($arg.elem);//操作区域
                        operation.$elem.after('<div class="tsf-status-area"></div>');
                        operation.$status = $('.tsf-status-area');
                        $.each(backData.data,function (i,o) {
                            if(o.action!='query'){
                                operation.$elem.append('<button type="button" btn-code="'+o.id+'" '+(isEmpty(o.operationCode)?'':'operation-code="'+o.operationCode+'"')+' '+(isEmpty(o.operationState)?'':'status="'+o.operationState+'"')+' check-num="'+o.checkNum+'" '+(o.checkNum>0?'disabled':'')+' class="layui-btn layui-btn-sm" is-task="'+o.isTask+'"><i class="'+o.icon+'"></i>'+o.name+'</button>');
                                if(!isEmpty(o.action)){
                                    $('button[btn-code="'+o.id+'"]').click(function () {
                                        if(!isEmpty($(this).attr('disabled'))){show_error('当前数据状态不允许此操作');return;}
                                        var warg = o.action.split('-');
                                        switch (warg[0]){
                                            case 'defOpen':
                                                var urlarg = '';
                                                if(o.checkNum>0){
                                                    var ids = getIds();
                                                    if(ids.length==0){show_msg('请选择您要操作的记录');return;}
                                                    if(o.url.indexOf('?')==-1){urlarg += '?id='+ids.join(',');}else{urlarg += '&id='+ids.join(',');}
                                                }
                                                openwin(o.url+urlarg,o.name,$.extend({},$arg.winArg,{area:[warg[1]+'px', warg[2]+'px']}));
                                                break;
                                            case 'defDelete':
                                                var parg = '';
                                                if(o.checkNum>0){
                                                    var ids = getIds();
                                                    if(ids.length==0){show_msg('请选择您要操作的记录');return;}
                                                    parg+=ids.join(',');
                                                }
                                                delete_inquiry('您确定要删除此操作记录？',o.url,{'id':parg},function () {
                                                    reloadList();
                                                    show_success('操作成功');
                                                });
                                                break;
                                            default:
                                                eval(warg+"(o)");
                                                break;
                                        }
                                    });
                                }
                            }
                        });
                        operation.$check1 = operation.$elem.find('button[check-num="1"]');
                        operation.$check2 = operation.$elem.find('button[check-num="2"]');
                        operation.$statusOper = operation.$elem.find('button[status]');
                        //启用表格查询
                        if($arg.listQuery){
                            //任务参数赋值
                            var lmid = getUrlParam('mid');
                            if(!isEmpty(lmid)){
                                var taskQueryParams = getLocalStorage('TASK_'+lmid);
                                if(!isEmpty(taskQueryParams)){
                                    cleanLocalStorage('TASK_'+lmid);
                                    form.val('queryForm',JSON.parse(taskQueryParams));
                                }
                            }
                            //开启列筛选
                            if($arg.listCols){
                                operation.$elem.parent().append('<div class="choice-btn layui-form pull-right"><button type="button" id="choiceColumn" class="layui-btn layui-btn-primary"><i class="fa fa-th"></i><i class="fa fa-caret-down"></i></button></div>');
                                var storKey = Base64.encode($arg.listQueryArg.url.split('?')[0]),cache={},storCol=getLocalStorage(storKey);
                                $.each($arg.listQueryArg.cols[0],function (i,o) {
                                    o['z-idx'] = i;
                                });
                                if(!isEmpty(storCol)){
                                    cache = JSON.parse(storCol);
                                    $.each($arg.listQueryArg.cols[0],function (i,o) {
                                        if(!o.fixed && typeof(cache[o.field])!='undefined'){
                                            o.hide = cache[o.field]['h'];
                                            o['z-idx'] = cache[o.field]['i'];
                                        }
                                    });
                                }
                                $('.choice-btn').click(function (event){event.stopPropagation();});
                                $('#choiceColumn').click(function(event){
                                    event.stopPropagation();
                                    if($('.layui-table-tool-panel').size()>0){return;}
                                    var $that = $(this),cols = ['<ul class="layui-table-tool-panel sortable">'];
                                    $arg.listQueryArg.cols[0].sort(function (a,b) {return a['z-idx'] - b['z-idx'];});
                                    $.each($arg.listQueryArg.cols[0],function (i,o) {
                                        if(!o.fixed){
                                            cache[o.field] = {'h':o.hide,'i':o['z-idx']};
                                            cols.push('<li><div><input type="checkbox" z-idx="'+o['z-idx']+'" name="'+o.field+'" title="'+o.title+'" '+(o.hide?'':'checked')+' lay-skin="primary" lay-filter="TSF-TABLE-COLS"></div></li>');
                                        }
                                    });
                                    cols.push('</ul>');
                                    $that.parent().append(cols.join(''));

                                    form.render('checkbox');
                                    form.on('checkbox(TSF-TABLE-COLS)',function () {
                                        var $that = this;
                                        cache[$that.name]['h'] = !$that.checked;
                                        cache[$that.name]['i'] = $($that).attr('z-idx');
                                        setLocalStorage(storKey,JSON.stringify(cache));
                                        $.each($arg.listQueryArg.cols[0],function (i,o) {
                                            if(!o.fixed && typeof(cache[o.field])!='undefined'){
                                                o.hide = cache[o.field]['h'];
                                                o['z-idx'] = cache[o.field]['i'];
                                            }
                                        });
                                        $arg.listQueryArg.cols[0].sort(function (a,b) {return a['z-idx'] - b['z-idx'];});
                                        $listTab.reload({cols:$arg.listQueryArg.cols});
                                    });

                                    $(".sortable").sortable({
                                        stop: function(event, ui) {
                                            var items = $('.sortable li input[type="checkbox"]');
                                            var minIdx = 999999;
                                            $.each(items,function (i,o){
                                                var zidx = parseInt($(o).attr('z-idx'));
                                                if(minIdx>zidx){
                                                    minIdx = zidx;
                                                }
                                            });
                                            $.each(items,function (i,o){
                                                var $that = $(o);
                                                $that.attr({'z-idx':minIdx+i});
                                                cache[$that.attr('name')]['h'] = !$that.attr('checked');
                                                cache[$that.attr('name')]['i'] = minIdx+i;
                                            });
                                            setLocalStorage(storKey,JSON.stringify(cache));
                                            $.each($arg.listQueryArg.cols[0],function (i,o) {
                                                if(!o.fixed && typeof(cache[o.field])!='undefined'){
                                                    o.hide = cache[o.field]['h'];
                                                    o['z-idx'] = cache[o.field]['i'];
                                                }
                                            });
                                            $arg.listQueryArg.cols[0].sort(function (a,b) {return a['z-idx'] - b['z-idx'];});
                                            $listTab.reload({cols:$arg.listQueryArg.cols});
                                        }
                                    }).disableSelection();
                                });
                                $arg.listQueryArg.cols[0].sort(function (a,b) {return a['z-idx'] - b['z-idx'];});
                            }
                            var $listTab = table.render($.extend({},{
                                elem: '#table-list',where:$('.query-form').serializeJson(),method:'post',
                                height: 'full-'+($('.tsf-list-top').height()+20),page: true,
                                limits: limits,limit:limit,id:'tab-list',response:{msgName:'message',statusCode: '1'}
                            },$arg.listQueryArg,{done:function (tres) {
                                    operation.listDone();
                                    operation.bindCopy();
                                    operation.bindTask();
                                    operation.autoTask();
                                    operation.queryStatus($arg,tres);
                                    $arg.listQueryDone(tres,backData.data);
                                }}));
                            table.on('checkbox(table-list)', function(obj){
                                operation.listDone();
                            });
                            var taskwin=null,statuswin=null;
                            table.on('tool(table-list)', function(item){
                                var rowData = item.data;
                                if(item.event === 'taskOperation'){
                                    operation.clearCheck(rowData.id);
                                    var $this = $(this);
                                    layer.close(taskwin);
                                    var outState = $this.attr('taskstate'),offset = $this.offset();
                                    taskwin = layer.open({offset: [(offset.top-14)+'px', (offset.left+$this.width()+10)+'px'],shade :0,anim:3,content:'<div class="task-buts"></div>',title:false,resize:false,type: 1,zIndex: layer.zIndex});
                                    var bsize = 0,$task = $('.task-buts');
                                    $.each(backData.data,function (s,f) {
                                        if(f.isTask&&!isEmpty(f.operationState)){
                                            if(contain(f.operationState.split(","),outState)){
                                                $task.append('<button type="button" oper-code="'+f.id+'" class="layui-btn layui-btn-xs"><i class="'+f.icon+'"></i>'+f.name+'</button>');
                                                bsize++;
                                                $('button[oper-code="'+f.id+'"]').click(function () {
                                                    $('button[btn-code="'+f.id+'"]').click();
                                                    layer.close(taskwin);
                                                });
                                            }
                                        }
                                    });
                                    if(bsize==0){layer.close(taskwin);show_msg("没有任何操作,请刷新页面");return;}
                                }else if(item.event === 'statusOperation'){
                                    layer.close(statuswin);
                                    statuswin = openwin('status/list.html?docId='+rowData.id,null,{
                                        area:['360px','520px'],shadeClose:true
                                    });
                                }else if(item.event === 'decStatusOperation'){
                                    layer.close(statuswin);
                                    statuswin = openwin('declare/status/list.html?docId='+rowData.id,null,{
                                        area:['360px','520px'],shadeClose:true
                                    });
                                }else{
                                    $arg.toolClick(this,item.event,rowData);
                                }
                            });
                            $('.search-btn').click(function () {
                                $listTab.reload({page:{curr:1},height: 'full-'+($('.tsf-list-top').height()+20),where:$('.query-form').serializeJson()});
                            });
                            var $moreQtyBtn = $('.more-qty-btn');
                            if($moreQtyBtn.size()>0){
                                var $moreQty = $('.more-qty');
                                $moreQtyBtn.click(function () {
                                    $moreQty.slideToggle(function () {
                                        $moreQtyBtn.html(($moreQty.css('display')=='none')?'展开<i class="fa fa-chevron-down"></i>':'收起<i class="fa fa-chevron-up"></i>');
                                    });
                                });
                            }
                        }
                    }else{
                        window.parent.parent.closeTab($arg.mid,'对不起您没有此权限,请联系贵司管理员授权');
                    }
                }
            });
        },
        listDone:function () {
            if(operation.$check1.length==0&& operation.$check2.length==0){return;}
            //选中的数据
            var datas = table.checkStatus('tab-list').data;
            if(datas.length==0){
                operation.$check1.attr({'disabled':true});
                operation.$check2.attr({'disabled':true});
            }else if(datas.length==1){
                operation.$check1.attr({'disabled':null});
                operation.$check2.attr({'disabled':null});
            }else{
                operation.$check1.attr({'disabled':true});
                operation.$check2.attr({'disabled':null});
            }
            //状态控制
            if(operation.$statusOper.length==0){return;}
            if(datas.length>0){
                //选中数据是否有状态
                var mixed = datas[0]['statusId'] || '';
                if(isEmpty(mixed)){
                    //禁用所有需要状态的按钮
                    operation.$statusOper.attr({'disabled':true});
                    return;
                }
                $.each(datas,function (s,d) {
                    var dstatusId = d['statusId'];
                    $.each(operation.$statusOper,function (n,m) {
                        var $sta = $(m);
                        //已经禁用的不处理
                        if(isEmpty($sta.attr('disabled'))){
                            $sta.attr({'disabled':contain($sta.attr('status').split(','),dstatusId)?null:true});
                        }
                    });
                });
            }
        },
        bindCopy:function () {
            $(".copy").parent().append('<a class="copy-btn" title="复制"><i class="fa fa-copy"></i></a>');
            $(".copy-btn").click(function () {
                var $self = $(this);
                operation.$copy.val(trim($self.parent().text())).select();
                document.execCommand("copy");
                layer.tips('已复制', $self.parent(),{tips: [1,'#333'], time: 2000});
            });
        },
        bindTask:function () {
            if(operation.$statusOper.length==0){return;}
            var allStatus = [];
            $.each(operation.$statusOper,function (i,o) {
                if($(o).attr('is-task')=='true'){
                    $.each($(o).attr('status').split(','),function (j,k) {
                        if(!contain(allStatus,k)){
                            allStatus.push(k);
                        }
                    });
                }
            });
            $.each($('.task'),function (i,o) {
                var $this = $(o);
                if(contain(allStatus,$this.attr('taskstate'))){
                    $this.show();
                }
            });
        },
        autoTask:function(){
            var autoTask = getLocalStorage('AUTO_TASK');
            if(!isEmpty(autoTask)){
                cleanLocalStorage('AUTO_TASK');
                var atObj = JSON.parse(autoTask);
                operation.clearCheck(atObj.documentId);
                $('button[operation-code="'+atObj.operation+'"]').click();
            }
        },
        queryStatus: function($arg,data){
            if(isNotEmpty($arg.statusTotal)&&isNotEmpty($arg.statusElementId)){
                operation.$status.html('');
                if(data.count>0){
                    $.post($arg.statusTotal,$('.query-form').serializeJson(),function (res) {
                        if(res.code=='1'&&res.data.length){
                            let statusMap = {};
                            $.each(res.data,function (i,o) {
                                statusMap[o.statusId] = o;
                            });
                            var shtml = [],total=0;
                            $.each($($arg.statusElementId).find('option'),function (i,o) {
                               var _key = $(o).val(),_val = $(o).text();
                               if(isNotEmpty(_key)&&isNotEmpty(statusMap[_key])){
                                   if(statusMap[_key].isStatistics){
                                       total+=statusMap[_key].total;
                                   }
                                   shtml.push('<a href="javascript:" class="'+_key+'" status-id="'+_key+'">'+_val+'('+statusMap[_key].total+')</a>');
                               }
                            });
                            operation.$status.html('<a href="javascript:" class="def-a" status-id="">全部('+total+')</a>'+shtml.join(''));
                            operation.$status.find('a').click(function () {
                                form.val('queryForm',{'statusId':$(this).attr('status-id')});
                                reloadList();
                            });
                        }
                    });
                }
            }
        },
        clearCheck:function (id) {
            var tabDatas = table.cache["tab-list"];
            for(var i=0;i< tabDatas.length;i++){
                var index= tabDatas[i]['LAY_TABLE_INDEX'];
                tabDatas[i]["LAY_CHECKED"] = false;
                $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', false);
                $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().removeClass('layui-form-checked');
                if(!isEmpty(id)&&tabDatas[i].id==id){
                    tabDatas[i]["LAY_CHECKED"] = true;
                    $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                    $('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                }
            }
            operation.listDone();
        }
    };
    app.obtainSubject(function (sub) {
        if(sub.tenantOpenVersion=='free'){//体验版
            $("<link>").attr({ rel: "stylesheet",type: "text/css",href: rurl('css/free-version.css')}) .appendTo("head");
        }
    });
    exports('operation', operation);
});
function reloadList(){$('.search-btn').click();}
function getCheckDatas(elem){return layui.table.checkStatus((elem || 'tab-list')).data;}
function getIds(elem){var id = [];var datas = getCheckDatas(elem);$.each(datas,function (i,o) {id.push(o.id);});return id;}
function getDatas(elem){return layui.table.checkStatus((elem || 'tab-list')).data;}
function isAllowOperation(mdata,operationCode){for(var i=0;i<mdata.length;i++){if(operationCode==mdata[i].operationCode){return true;}}return false;}
function requestTips(o,msg) {
    var ids = getIds();
    if(ids.length==0){show_msg('请选择您要操作的记录');return;}
    delete_inquiry(msg,o.url,{'id':ids.join(',')},function () {
        reloadList();show_success('操作成功');
    });
}
